package com.xinqi.modules.prepare.data.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.common.security.utils.UserHelp;
import com.xinqi.modules.prepare.common.dto.data.PrepareDataData;
import com.xinqi.modules.prepare.common.service.PrepareAuthService;
import com.xinqi.modules.prepare.data.convert.PrepareDataConvert;
import com.xinqi.modules.prepare.data.domain.PrepareDataEntity;
import com.xinqi.modules.prepare.data.dto.req.PrepareDataCreateDTO;
import com.xinqi.modules.prepare.data.dto.req.PrepareDataDeleteDTO;
import com.xinqi.modules.prepare.data.dto.req.PrepareDataQueryDTO;
import com.xinqi.modules.prepare.data.dto.req.PrepareDataUpdateDTO;
import com.xinqi.modules.prepare.data.dto.rsp.PrepareDataResultDTO;
import com.xinqi.modules.prepare.data.manager.PrepareDataManager;
import com.xinqi.modules.prepare.data.service.PrepareDataService;
import com.xinqi.modules.prepare.folder.domain.PrepareFileFolderEntity;
import com.xinqi.modules.prepare.folder.manager.PrepareFileFolderManager;
import com.xinqi.modules.prepare.prepare.enums.PrepareMemberPermissionEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareOperateTypeEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareSubOperateTypeEnum;
import com.xinqi.modules.prepare.prepare.manager.PrepareOperateLogManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 备课区资料服务层实现
 *
 * @author: system
 * @date: 2023/03/19
 */
@Validated
@Service("prepareDataService")
@RequiredArgsConstructor
public class PrepareDataServiceImpl implements PrepareDataService {
    private final PrepareDataConvert prepareDataConvert;
    private final PrepareDataManager prepareDataManager;
    private final PrepareAuthService prepareAuthService;
    private final PrepareFileFolderManager prepareFileFolderManager;
    private final PrepareOperateLogManager prepareOperateLogManager;

    /**
     * 分页查询 备课区资料数据
     */
    @Override
    @DS("slaver")
    public PageInfo<PrepareDataResultDTO> page(Param pageable, PrepareDataQueryDTO query) {
        IPage<PrepareDataEntity> page = prepareDataManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, prepareDataConvert::convert);
    }

    /**
     * 查询 备课区资料数据
     */
    @Override
    public List<PrepareDataResultDTO> find(PrepareDataQueryDTO query) {
        return prepareDataManager.list(wrapper(query)).stream()
            .map(prepareDataConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<PrepareDataEntity> wrapper(PrepareDataQueryDTO query) {
        LambdaQueryWrapper<PrepareDataEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(PrepareDataEntity::getId, v));
        Queries.accept(query.getPrepareId(), v -> wrapper.eq(PrepareDataEntity::getPrepareId, v));
        return wrapper;
    }

    /**
     * 根据id查询 备课区资料数据
     */
    @Override
    public PrepareDataResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(prepareDataManager.findById(id)).map(prepareDataConvert::convert).orElse(null);
    }

    @Override
    public PrepareDataData find(Long id) {
        return prepareDataConvert.convert(findById(id));
    }

    /**
     * 新增 备课区资料数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid PrepareDataCreateDTO dto) {
        prepareAuthService.check(dto.getPrepareId(), PrepareMemberPermissionEnum.新建);
        if (dto.getIsAutoGenerateName() == null) {
            dto.setIsAutoGenerateName(false);
        }
        PrepareDataEntity entity = prepareDataConvert.create(dto);
        entity.setUserId(UserHelp.userId());
        prepareDataManager.save(entity);
        // 创建备课区文件
        PrepareFileFolderEntity file = prepareFileFolderManager.insertFile(entity, entity.getPrepareId(),
            dto.getFolderId(), dto.getIsAutoGenerateName());
        prepareOperateLogManager.addFileOperateLog(entity, PrepareOperateTypeEnum.FILE_EDIT, PrepareSubOperateTypeEnum.ADD);
        // 如果 名称 不相等，则更新文件名
        if (!Objects.equals(entity.getName(), file.getName())) {
            entity.setName(file.getName());
            prepareDataManager.updateById(entity);
        }
        return entity.getId();
    }

    @Override
    public Long insert(PrepareDataData data) {
        PrepareDataCreateDTO dto = prepareDataConvert.create(data);
        return insert(dto);
    }

    /**
     * 根据id修改 备课区资料数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid PrepareDataUpdateDTO dto) {
        PrepareDataEntity old = Optional.ofNullable(prepareDataManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        prepareAuthService.check(old.getPrepareId(), PrepareMemberPermissionEnum.编辑);
        PrepareDataEntity entity = prepareDataConvert.update(dto);
        boolean b = prepareDataManager.updateById(entity);
        if (b) {
            // 更新备课区文件
            PrepareDataEntity newEntity = prepareDataManager.getById(dto.getId());
            prepareFileFolderManager.updateFile(newEntity, newEntity.getPrepareId());
            prepareOperateLogManager.addFileOperateLog(newEntity, PrepareOperateTypeEnum.FILE_EDIT, PrepareSubOperateTypeEnum.EDIT);
        }
        return b;
    }

    /**
     * 根据id删除 备课区资料数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        PrepareDataEntity entity = Optional.ofNullable(prepareDataManager.getById(id))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        prepareAuthService.check(entity.getPrepareId(), PrepareMemberPermissionEnum.删除);
        boolean b = prepareDataManager.deleteById(entity);
        if (b) {
            // 删除备课区文件
            prepareFileFolderManager.deleteFile(entity, entity.getPrepareId());
        }
        return b;
    }

    /**
     * 根据id删除 备课区资料数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(PrepareDataDeleteDTO dto) {
        return deleteById(dto.getId());
    }

}
